package com.ada.rabbitmq;

import com.google.common.collect.ImmutableMap;
import com.rabbitmq.client.*;

public class DelayedQueueExample {
    private static final String QUEUE_NAME = "my_queue";
    private static final String DELAYED_QUEUE_NAME = "delayed_queue";
    private static final String DELAYED_EXCHANGE_NAME = "delayed_exchange";
    private static final String DELAYED_ROUTING_KEY = "delayed_routing_key";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.108");
        factory.setUsername("ada");
        factory.setPassword("123456");
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            // 创建普通队列并设置 TTL
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            channel.queueDeclare(DELAYED_QUEUE_NAME, false, false, false, null);

            // 设置队列的 TTL（以毫秒为单位，比如设置为 5000 毫秒，即 5 秒）
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            channel.queueDeclare(DELAYED_QUEUE_NAME, false, false, false, null);

            // 设置原始队列的 x-dead-letter-exchange 和 x-dead-letter-routing-key 属性
            channel.queueDeclare(QUEUE_NAME, false, false, false, 
                ImmutableMap.of("x-dead-letter-exchange", DELAYED_EXCHANGE_NAME, "x-dead-letter-routing-key", DELAYED_ROUTING_KEY));

            // 创建死信交换机
            channel.exchangeDeclare(DELAYED_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            // 将死信队列绑定到死信交换机
            channel.queueBind(DELAYED_QUEUE_NAME, DELAYED_EXCHANGE_NAME, DELAYED_ROUTING_KEY);

            // 发送消息到普通队列
            String message = "Hello, RabbitMQ!";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
        }
    }
}
